<template>
  <div>
    <Card>
      <vxe-grid
        highlight-hover-row
        show-header-overflow
        show-overflow
        ref="xGrid"
        height="600"
        align="center"
        :columns="tableColumn"
        :data="tableData"
        :toolbar-config="tableToolbar"
        :edit-config="{
          trigger: 'manual',
          mode: 'row',
          showStatus: true,
          icon: 'fa fa-file-text-o',
        }"
      >
        <template #form>
          <Row :gutter="16">
            <Col span="6">
              园区名：
              <Input v-model="formData.park_name" placeholder="请输入内容" />
            </Col>
            <Col span="6">
              地址：
              <Input v-model="formData.address" placeholder="请输入内容" />
            </Col>
          </Row>
        </template>
        <template #toolbar_buttons>
          <Button
            type="primary"
            icon="ios-search"
            style="margin-right: 10px"
            @click="search()"
            >查询
          </Button>
          <Button
            type="primary"
            style="margin-right: 10px"
            icon="md-refresh"
            @click="refreshTable()"
            >刷新
          </Button>
          <Button type="error" style="margin-right: 10px" @click="deleteList()"
            >批量删除
          </Button>
        </template>
        <template #operate="{ row }">
          <Button
            type="primary"
            style="margin-right: 10px"
            @click="editRow(row)"
            >编辑
          </Button>
          <Button
            type="error"
            style="margin-right: 10px"
            @click="deleteRow(row)"
            >删除
          </Button>
        </template>

        <template #pager>
          <div style="text-align: center; padding: 10px">
            <Page
              :current="page.current"
              :total="page.total"
              :page-size="page.pageSize"
              show-elevator
              show-total
              show-sizer
              @on-change="refresh"
            />
          </div>
        </template>

      </vxe-grid>

      <vxe-modal v-model="showEdit" :title="'编辑&保存'" width="800" min-width="600" min-height="300" :loading="submitLoading" resize destroy-on-close>
      <template #default>
        <vxe-form :data="formData" :items="formItems" :rules="formRules" title-align="right" title-width="100" @submit="submitEvent"></vxe-form>
      </template>
    </vxe-modal>
    </Card>
  </div>
</template>

<script>
import axios from '@/libs/api.request'
import { update } from 'countup'
export default {
  data () {
    return {
      showEdit: false,
      submitLoading: false,
      selectRow: null,
      formData: {
        park_name: '',
        brief_introduction: '',
        contact_details: '',
        province: '',
        city: '',
        area: '',
        address: '',
        status: '',
        create_time: '',
        update_time: ''
      },
      tableToolbar: {
        zoom: true,
        custom: true,
        slots: {
          buttons: 'toolbar_buttons',
          tools: 'toolbar_tools'
        }
      },
      tableColumn: [
        { type: 'checkbox', width: 40, fixed: 'left' },
        { field: 'park_name', title: '园区名称', width: 120 },
        { field: 'brief_introduction', title: '园区简介', width: 200 },
        { field: 'contact_details', title: '联系方式', width: 120 },
        { field: 'province', title: '省', width: 80 },
        { field: 'city', title: '市', width: 80 },
        { field: 'area', title: '区', width: 80 },
        { field: 'address', title: '详细地址', width: 200 },
        // { field: 'status', title: '状态', width: 80 },
        { field: 'create_time', title: '创建时间', width: 180 },
        { field: 'update_time', title: '修改时间', width: 180 },
        {
          title: '操作',
          width: 180,
          slots: { default: 'operate' },
          fixed: 'right'
        }
      ],
      page: {
        current: 1,
        total: 100,
        pageSize: 10
      },
      tableData: [
        {
          id: '',
          park_name: '测试园区',
          brief_introduction:
            '这是一个条很长的简介，这是一个条很长的简介，这是一个条很长的简介，这是一个条很长的简介，这是一个条很长的简介',
          contact_details: '15274858582',
          province: '湖南省',
          city: '长沙市',
          area: '天心区',
          address: '中南大学铁道学院',
          // status: '1',
          create_time: '2021-04-27 22:11:14',
          update_time: '2021-04-27 22:11:14'
        }
      ],
      formRules: {
        name: [
          { required: true, message: '请输入名称' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符' }
        ],
        nickname: [
          { required: true, message: '请输入昵称' }
        ],
        sex: [
          { required: true, message: '请选择性别' }
        ]
      },
      formItems: [
        { title: '基本信息', span: 24, titleAlign: 'left', titleWidth: 200, titlePrefix: { icon: 'fa fa-address-card-o' } },
        { field: 'park_name', title: '园区名称', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入园区名称' } } },
        // { field: 'nickname', title: 'Nickname', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入昵称' } } },
        { field: 'brief_introduction', title: '园区简介', span: 24, itemRender: { name: '$textarea', props: { autosize: { minRows: 2, maxRows: 4 }, placeholder: '请输入地址' } } },
        { field: 'contact_details', title: '联系方式', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入联系方式' } } },

        { field: 'province', title: '省', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入省' } } },
        { field: 'city', title: '市', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入市' } } },
        { field: 'area', title: '区', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入区' } } },

        // { field: 'city', title: '市', span: 12, itemRender: { name: '$radio', options: [{ label: '是', value: 'Y' }, { label: '否', value: 'N' }] } },
        // { field: 'area', title: '区', span: 24, visibleMethod: this.visibleMethod, itemRender: { name: '$checkbox', options: [{ label: '运动、跑步', value: '1' }, { label: '听音乐', value: '2' }, { label: '泡妞', value: '3' }, { label: '吃美食', value: '4' }] } },
        // { title: 'Other information', span: 24, titleAlign: 'left', titleWidth: 200, titlePrefix: { message: '请填写必填项', icon: 'fa fa-info-circle' } },
        // { field: 'num', title: 'Number', span: 12, itemRender: { name: '$input', props: { type: 'number', placeholder: '请输入数值' } } },
        // { field: 'date3', title: 'Date', span: 12, itemRender: { name: '$input', props: { type: 'date', placeholder: '请选择日期' } } },
        { field: 'address', title: '详细地址', span: 24, titleSuffix: { message: '提示信息！！', icon: 'fa fa-question-circle' }, itemRender: { name: '$textarea', props: { autosize: { minRows: 2, maxRows: 4 }, placeholder: '请输入详细地址' } } },
        { align: 'center', span: 24, titleAlign: 'left', itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '提交', status: 'primary' } }, { props: { type: 'reset', content: '重置' } }] } }
      ]

    }
  },
  mounted () {
    console.log('mounted')
    this.update()
  },

  methods: {
    update () {
      this.get_park_list()
    },
    toLine (name) {
      return name.replace(/([A-Z])/g, '_$1').toLowerCase()
    },
    submitEvent () {
      this.submitLoading = true
      setTimeout(() => {
        // const $table = this.$refs.xGrid
        console.log(this.formData)
        this.submitLoading = false
        this.showEdit = false
        this.$XModal.message({ content: '保存成功', status: 'success' })
        // Object.assign(this.selectRow, this.formData)
      }, 500)
      this.update_park()
    },
    update_park () {
      return new Promise((resolve, reject) => {
        axios.request({
          method: 'post',
          url: 'park/update',
          data: {
            id: this.formData.id,
            parkName: this.formData.parkName,
            briefIntroduction: this.formData.briefIntroduction,
            introduction: this.formData.introduction,
            parkImage: this.formData.parkImage,
            contactDetails: this.formData.contactDetails,
            province: this.formData.province,
            city: this.formData.city,
            area: this.formData.area,
            address: this.formData.address,
            longitude: this.formData.longitude,
            latitude: this.formData.latitude
          }
        }).then(res => {
          console.log(res)
          resolve()
        }).catch(err => {
          console.log(err)
          reject(err)
        })
      })
    },
    get_park_list () {
      return new Promise((resolve, reject) => {
        axios.request({
          method: 'get',
          url: 'park/all'
          // data: {
          //   pageSize: this.page.pageSize,
          //   pageNum: this.page.current
          // }
        }).then(res => {
          const resDatas = res.data.msg
          console.log(resDatas, resDatas.length)
          var tableData = []
          for (var i = 0; i < resDatas.length; i++) {
            // console.log(resDatas[i])
            var temp = { id: '' }
            for (var key in resDatas[i]) {
              for (var itemName in this.tableData[0]) {
                // console.log(this.underline(key), itemName)
                if (this.toLine(key) === itemName) {
                  temp[itemName] = resDatas[i][key]
                }
              }
            }
            // console.log('temp', temp)
            tableData.push(temp)
          }
          this.tableData = tableData
          // this.tableData = this.tableData.concat([
          // ])
          // this.tableData =
          // const resData = res.data
          // commit('setToken', resData.msg)
          resolve()
        }).catch(err => {
          console.log(err)
          reject(err)
        })
      })
    },

    get_park_list_query () {
      return new Promise((resolve, reject) => {
        axios.request({
          method: 'get',
          url: 'park/query',
          data: {
            pageSize: this.page.pageSize,
            pageNum: this.page.current
          }
        }).then(res => {
          const resDatas = res.data.msg
          console.log(resDatas, resDatas.length)
          var tableData = []
          for (var i = 0; i < resDatas.length; i++) {
            // console.log(resDatas[i])
            var temp = { id: '' }
            for (var key in resDatas[i]) {
              for (var itemName in this.tableData[0]) {
                // console.log(this.underline(key), itemName)
                if (this.toLine(key) === itemName) {
                  temp[itemName] = resDatas[i][key]
                }
              }
            }
            // console.log('temp', temp)
            tableData.push(temp)
          }
          this.tableData = tableData
          // this.tableData = this.tableData.concat([
          // ])
          // this.tableData =
          // const resData = res.data
          // commit('setToken', resData.msg)
          resolve()
        }).catch(err => {
          console.log(err)
          reject(err)
        })
      })
    },
    get_park_info () {
      axios.request({
        method: 'get',
        url: 'park/info/access', //
        data: {
          parkId: 1
        }
        // params: { // 类似地址栏传参
        //   parkId: 1
        // }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },
    search () {
      this.get_park_info()
      // console.log(row)
      // console.log('search')
      // this.get_park_list()
    },
    refreshTable () {
      this.get_park_list()
      // console.log(row)
    },
    deleteList (row) {
      // 获取选中的数据
      const selectedRecords = this.$refs.xGrid.getCheckboxRecords()
      console.log(selectedRecords)
    },
    editRow (row) {
      // console.log(row, 'hello')
      this.showEdit = true
      this.selectRow = row
      this.formData = row
      // axios.request({
      //   method: 'post',
      //   url: 'park/update', //
      //   data: {
      //     row // 显示少了经纬度，经纬度应该是 根据地区去计算只能够从后端来接受（不给修改）还是可以让用户自己修改？
      //   }
      //   // params: { // 类似地址栏传参
      //   //   parkId: 1
      //   // }
      // }).then(res => {
      //   console.log(res)
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    deleteRow (row) {
      this.$Modal.confirm({
        title: '操作确认',
        content: '您确定要删除"' + row.park_name + '"吗',
        onOk: () => {
          var idx = 0
          idx = this.tableData.indexOf(row)
          // 这里的bug 就是 在这里输出的时候，this.tableData里面的数据以及被删除了，
          this.tableData.splice(idx, 1) // 返回删除元素的数组
          this.$Message.success('删除成功')
          // console.log('1111111', idx, this.tableData)
        },
        onCancel: () => {}
      })
    }
  }
}
</script>
